<?php
class LoanSearch extends CFormModel {
	public $bank;
	public $productName;
	public $customerName;
	public $discharged;
	public $dischargeDateMin;
	public $dischargeDateMax;
	public $commissionPaid;
	public $honeymoonDateMin;
	public $honeymoonDateMax;
	public $settlementDateMin;
	public $settlementDateMax;
	public $createDateMin;
	public $createDateMax;
	public $amountMin;
	public $amountMax;
	public $rateMin;
	public $rateMax;
	public $pricingMin;
	public $pricingMax;
	public $teamId;
	public $hidden;

	public function rules()
	{
		return array(
			array('commissionPaid, teamId, hidden', 'numerical', 'integerOnly'=>true),
			array('amountMin, amountMax, rateMin, rateMax, pricingMin, pricingMax', 'numerical'),
			array('bank, productName, customerName', 'length', 'max'=>255),
			array('discharged, dischargeDateMin, dischargeDateMax, honeymoonDateMin, honeymoonDateMax, settlementDateMin, settlementDateMax,
			createDateMin, createDateMax', 'safe'),
		);
	}
	
	public function attributeLabels()
	{
		return array(
			'bank' => 'Bank',
			'amountMin' => 'Amount ($)',
			'settlementDateMin' => 'Settlement Date',
			'rateMin' => 'Rate (%)',
			'productName' => 'Product Name',
			'pricingMin' => 'Pricing',
			'honeymoonDateMin' => 'Honeymoon Date',
			'dischargeDate' => 'Discharge Date',
			'discharged' => 'Discharged',
			'createDateMin' => 'Create Date',
			'commissionPaid' => 'Commission Paid',
			'note' => 'Note',
			'customerName' => 'Customer Name',
			'teamId' => 'Team',
		);
	}
	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		return new CActiveDataProvider('Loan', array(
			'criteria'=>$this->createCriteria(),
		));
	}
	
	/**
	 * Create criteria for the search.
	 * @throws CHttpException if user cannot access the organization
	 * @return CDbCriteria the CDbCriteria to match this search
	 */
	public function createCriteria(){
		$criteria=new CDbCriteria;
		$criteria->alias='loan';

		// Bank
		$criteria->compare('deal.bank',$this->bank,true);
		
		// Customer Name
		if(!empty($this->customerName)){
			$nameCriteria=new CDbCriteria;
			$customerNameParts=split(" ", trim($this->customerName),2);
			if(count($customerNameParts)==1){
				$nameCriteria->compare('customer.firstName',$customerNameParts[0],true,'OR');
				$nameCriteria->compare('customer.lastName',$customerNameParts[0],true,'OR');
			}elseif(count($customerNameParts)==2){
				$nameCriteria->compare('customer.firstName',$customerNameParts[0],true,'OR');
				$nameCriteria->compare('customer.lastName',$customerNameParts[1],true,'OR');
			}
			$nameCriteria->select = 'dealId';
			$nameCriteria->with = array('customer');
			$dealCustomers = DealCustomer::model()->findAll($nameCriteria);
			$dealIds = array();
			foreach ($dealCustomers as $dealCustomer) {
					$dealIds[] = $dealCustomer->dealId;
			}
			
			
			$criteria->addInCondition('deal.id', $dealIds);
			
		}

		// Team
		if(Yii::app()->user->checkAccess('manager')){
			// search for all loan or specified team
			$criteria->compare('deal.teamId',$this->teamId);
		}elseif(User::getCurrentUser()->teamLeader){
			// only search within the team
			$criteria->compare('deal.teamId',User::getCurrentUser()->teamId);
//			$this->teamId=User::getCurrentUser()->teamId;
		}else{
			//search within the user
			$criteria->compare('deal.createUserId',User::getCurrentUser()->id);
//			$this->teamId=User::getCurrentUser()->teamId;
		}

		// Product Name
		$criteria->compare('productName',$this->productName,true);
		
		// Honeymoon Date
		if(!empty($this->honeymoonDateMin)){
			$criteria->compare('honeymoonDate','>='.$this->transformDate($this->honeymoonDateMin));
		}
		if(!empty($this->honeymoonDateMax)){
			$criteria->compare('honeymoonDate','<='.$this->transformDate($this->honeymoonDateMax));
		}
		
		// Settlement Date
		if(!empty($this->settlementDateMin)){
			$criteria->compare('settlementDate','>='.$this->transformDate($this->settlementDateMin));
		}
		if(!empty($this->settlementDateMax)){
			$criteria->compare('settlementDate','<='.$this->transformDate($this->settlementDateMax));
		}
		
		// Create Date
		if(!empty($this->createDateMin)){
			$criteria->compare('loan.createDate','>='.$this->transformDate($this->createDateMin).' 00:00:00');
		}
		if(!empty($this->createDateMax)){
			$criteria->compare('loan.createDate','<='.$this->transformDate($this->createDateMax).' 23:59:59');
		}
		
		// Amount
		$criteria->compare('amount','>='.$this->amountMin);
		$criteria->compare('amount','<='.$this->amountMax);
		
		// Rate
		$criteria->compare('rate','>='.$this->rateMin);
		$criteria->compare('rate','<='.$this->rateMax);
		
		// Commission Paid
		$criteria->compare('commissionPaid',$this->commissionPaid);
		
		// Pricing
		$criteria->compare('pricing','>='.$this->pricingMin);
		$criteria->compare('pricing','<='.$this->pricingMax);
		
		// Discharged
		if($this->discharged===DataUtil::VALUE_YES){
			if(empty($this->dischargeDateMin)&&empty($this->dischargeDateMax)){
				$criteria->addNotInCondition('dischargeDate', array(null));
			}else{
				if(!empty($this->dischargeDateMin)){
					$criteria->compare('dischargeDate','>='.$this->dischargeDateMin);
				}
				if(!empty($this->dischargeDateMax)){
					$criteria->compare('dischargeDate','<='.$this->dischargeDateMax);
				}
			}
		}elseif($this->discharged===DataUtil::VALUE_NO){
			$criteria->addInCondition('dischargeDate', array(null));
		}

		// Hidden
		if(GlobalConfiguration::isManageMode()){
			$criteria->compare('hidden',$this->hidden);
		}else{
			$criteria->compare('hidden','0');
		}

		$criteria->with=array('deal');
		$criteria->order='settlementDate DESC';
		return $criteria;
	}
	
	
	protected function transformDate($dateString) {
		$timestamp=CDateTimeParser::parse($dateString,'d/M/yyyy',array('month'=>1,'day'=>1,'hour'=>0,'minute'=>0,'second'=>0));
		if($timestamp!==false)
		{
			return Yii::app()->dateFormatter->format('yyyy-M-d',$timestamp);
		}else{
			return $dateString;
		}
	}
}